import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

import { getToken } from '@/utils/auth'

import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

let token = getToken()
  if (token) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const userName = store.getters.userName
      if (userName) {
        next()
      } else {
        try {
          await store.dispatch('user/getUserInfo')
      
          const accessRoutes = await store.dispatch('permission/GenerateRoutes')
          
        //   router.addRoutes(accessRoutes)
          next()
        //   next({ ...to, replace: true })
        } catch (error) {
        //   await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // console.log('====================================');
    // console.log(to.path,'path');
    // console.log(whiteList.indexOf(to.path),'whiteList.indexOf(to.path)');
    // console.log('====================================');
    if (whiteList.indexOf(to.path) !== -1) {
        // 页面内登录
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      Message({
        message: '登陆信息已过期,请重新登录',
        type: 'error',
        duration: 5 * 1000
      })
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
